<template>
  <div class="order-page">
    <van-nav-bar title="订单确认" left-arrow @click-left="goBack" />
    
    <!-- 收货地址 -->
    <div class="address-section">
      <van-cell 
        title="收货地址" 
        is-link 
        @click="selectAddress"
        :value="selectedAddress ? selectedAddress.name + ' ' + selectedAddress.phone : '请选择收货地址'"
      />
    </div>
    
    <!-- 商品列表 -->
    <div class="goods-section">
      <div class="section-title">商品信息</div>
      <div class="goods-list">
        <div 
          v-for="item in orderItems" 
          :key="item.id" 
          class="goods-item"
        >
          <img :src="item.img" :alt="item.title" class="goods-image" />
          <div class="goods-info">
            <div class="goods-title">{{ item.title }}</div>
            <div class="goods-specs" v-if="item.specs">
              {{ formatSpecs(item.specs) }}
            </div>
            <div class="goods-price">
              <span class="price">¥{{ formatPrice(item.price) }}</span>
              <span class="count">x{{ item.count }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 优惠券 -->
    <div class="coupon-section">
      <van-cell 
        title="优惠券" 
        is-link 
        @click="selectCoupon"
        :value="selectedCoupon ? selectedCoupon.name : '暂无可用优惠券'"
      />
    </div>
    
    <!-- 订单信息 -->
    <div class="order-info">
      <div class="info-item">
        <span>商品总价</span>
        <span>¥{{ totalPrice.toFixed(2) }}</span>
      </div>
      <div class="info-item" v-if="selectedCoupon">
        <span>优惠券</span>
        <span>-¥{{ selectedCoupon.discount.toFixed(2) }}</span>
      </div>
      <div class="info-item">
        <span>运费</span>
        <span>¥{{ shipping.toFixed(2) }}</span>
      </div>
      <div class="info-item total">
        <span>实付金额</span>
        <span class="final-price">¥{{ finalPrice.toFixed(2) }}</span>
      </div>
    </div>
    
    <!-- 备注 -->
    <div class="remark-section">
      <van-field
        v-model="remark"
        label="备注"
        type="textarea"
        placeholder="请输入备注信息"
        rows="2"
        autosize
      />
    </div>
    
    <!-- 底部结算栏 -->
    <div class="bottom-bar">
      <div class="total-info">
        <span>合计: </span>
        <span class="price">¥{{ finalPrice.toFixed(2) }}</span>
      </div>
      <van-button type="danger" @click="submitOrder">提交订单</van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'
import { getSkusByIds } from '@/api/sku'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()

// 响应式数据
const selectedAddress = ref(null)
const selectedCoupon = ref(null)
const remark = ref('')
const shipping = ref(0)
const directPurchaseSku = ref(null)

// 订单商品
const orderItems = computed(() => {
  if (route.query.from === 'cart') {
    return cartStore.selectedItems
  } else {
    // 从商品详情直接购买
    const count = parseInt(route.query.count) || 1
    
    if (directPurchaseSku.value) {
      return [{
        id: directPurchaseSku.value.id,
        title: directPurchaseSku.value.title,
        img: directPurchaseSku.value.img,
        price: directPurchaseSku.value.actual_price, // 使用实际价格
        count: count,
        specs: directPurchaseSku.value.specs || []
      }]
    }
    
    return []
  }
})

// 商品总价
const totalPrice = computed(() => {
  return orderItems.value.reduce((total, item) => {
    return total + (item.price * item.count)
  }, 0)
})

// 最终价格
const finalPrice = computed(() => {
  let price = totalPrice.value + shipping.value
  if (selectedCoupon.value) {
    price -= selectedCoupon.value.discount
  }
  return Math.max(0, price)
})

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  return parseFloat(price).toFixed(2)
}

// 格式化规格
const formatSpecs = (specs) => {
  if (!specs || typeof specs !== 'object') return ''
  return Object.values(specs).join('、')
}

// 选择地址
const selectAddress = () => {
  // 这里应该跳转到地址选择页面
  showToast('地址选择功能开发中')
}

// 选择优惠券
const selectCoupon = () => {
  // 这里应该跳转到优惠券选择页面
  showToast('优惠券选择功能开发中')
}

// 提交订单
const submitOrder = async () => {
  if (!userStore.isLogin) {
    showToast('请先登录')
    router.push('/login')
    return
  }
  
  if (!selectedAddress.value) {
    showToast('请选择收货地址')
    return
  }
  
  // 检查收款码状态
  const { checkQrcodeStatus } = await import('@/utils/qrcode-validator')
  const qrcodeValid = await checkQrcodeStatus(router.push)
  
  if (!qrcodeValid) {
    return // 收款码验证失败，已显示提示并跳转
  }
  
  try {
    await showConfirmDialog({
      title: '确认订单',
      message: `确认支付 ¥${finalPrice.value.toFixed(2)} 吗？`
    })
    
    // 这里应该调用提交订单 API
    // const response = await submitOrderAPI({
    //   address: selectedAddress.value,
    //   items: orderItems.value,
    //   coupon: selectedCoupon.value,
    //   remark: remark.value,
    //   totalPrice: finalPrice.value
    // })
    
    showToast('订单提交成功')
    
    // 清空购物车中已购买的商品
    if (route.query.from === 'cart') {
      cartStore.clearSelected()
    }
    
    // 跳转到支付页面，传递订单数据
    router.push({
      path: '/payment-confirm',
      query: {
        totalPrice: totalPrice.value,
        shipping: shipping.value,
        couponDiscount: selectedCoupon.value ? selectedCoupon.value.discount : 0,
        finalPrice: finalPrice.value,
        orderNo: 'ORDER' + Date.now() // 生成订单号
      }
    })
  } catch {
    // 用户取消
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取直接购买的SKU信息
const getDirectPurchaseSkuInfo = async () => {
  const skuId = route.query.sku_id
  if (skuId) {
    try {
      console.log('获取订单页面SKU信息，ID:', skuId)
      const skus = await getSkusByIds(skuId)
      if (skus && skus.length > 0) {
        directPurchaseSku.value = skus[0]
        console.log('订单页面SKU信息:', directPurchaseSku.value)
      }
    } catch (error) {
      console.error('获取SKU信息失败:', error)
      showToast('获取商品信息失败')
    }
  }
}

// 组件挂载时初始化数据
onMounted(async () => {
  // 检查收款码状态（页面级验证）
  const { quickCheckQrcode } = await import('@/utils/qrcode-validator')
  const qrcodeCheck = await quickCheckQrcode()
  
  if (!qrcodeCheck.valid) {
    // 收款码状态不满足要求，显示提示并跳转
    showToast(qrcodeCheck.message)
    
    // 延迟跳转，让用户看到提示
    setTimeout(() => {
      router.push('/my-qrcode')
    }, 1500)
    
    return // 阻止页面继续加载
  }
  
  // 收款码验证通过，继续加载页面
  // 如果是直接购买，先获取SKU信息
  await getDirectPurchaseSkuInfo()
  
  // 模拟默认地址
  selectedAddress.value = {
    id: 1,
    name: '张三',
    phone: '13800138000',
    address: '北京市朝阳区xxx街道xxx小区'
  }
  
  // 模拟运费
  shipping.value = totalPrice.value > 99 ? 0 : 10
})
</script>

<style lang="scss" scoped>
.order-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 60px;
}

.address-section {
  background: #fff;
  margin-bottom: 10px;
}

.goods-section {
  background: #fff;
  margin-bottom: 10px;
  padding: 15px;
  
  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 15px;
  }
  
  .goods-list {
    .goods-item {
      display: flex;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .goods-image {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 4px;
        margin-right: 15px;
      }
      
      .goods-info {
        flex: 1;
        
        .goods-title {
          font-size: 14px;
          color: #333;
          margin-bottom: 5px;
          line-height: 1.4;
        }
        
        .goods-specs {
          font-size: 12px;
          color: #999;
          margin-bottom: 5px;
        }
        
        .goods-price {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .price {
            font-size: 16px;
            font-weight: bold;
            color: #ff6b6b;
          }
          
          .count {
            font-size: 14px;
            color: #999;
          }
        }
      }
    }
  }
}

.coupon-section {
  background: #fff;
  margin-bottom: 10px;
}

.order-info {
  background: #fff;
  margin-bottom: 10px;
  padding: 15px;
  
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    font-size: 14px;
    color: #333;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    &.total {
      border-top: 1px solid #f0f0f0;
      padding-top: 10px;
      font-weight: bold;
      
      .final-price {
        color: #ff6b6b;
        font-size: 18px;
      }
    }
  }
}

.remark-section {
  background: #fff;
  margin-bottom: 10px;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 10px 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  
  .total-info {
    font-size: 14px;
    color: #333;
    
    .price {
      font-size: 18px;
      font-weight: bold;
      color: #ff6b6b;
    }
  }
  
  .van-button {
    min-width: 120px;
  }
}
</style> 